package com.tech.common

import org.json4s.DefaultFormats
import org.json4s.jackson.JsonMethods

import java.io.{BufferedReader, IOException, InputStream, InputStreamReader, OutputStream}
import java.net.{HttpURLConnection, MalformedURLException, URL}
import scala.collection.mutable
import scala.language.postfixOps

object HttpUtils {

  def main(args: Array[String]): Unit = {

    println(doGet("http://52.130.64.87/ndev-portraitcenter/v1/customerProperties/getCustomPropertiesByEventKey?eventKey=$payment"))

    getHttpJson("$order")

    val stringToStringToString = initializeHttpBroadcast()


  }

  def doGet(httpurl: String): String = {
    var connection: HttpURLConnection = null
    var is: InputStream = null
    var br: BufferedReader = null
    var result: String = null // 返回结果字符串
    try { // 创建远程url连接对象
      val url = new URL(httpurl)
      // 通过远程url连接对象打开一个连接，强转成httpURLConnection类
      connection = url.openConnection.asInstanceOf[HttpURLConnection]
      // 设置连接方式：get
      connection.setRequestMethod("GET")
      // 设置连接主机服务器的超时时间：15000毫秒
      connection.setConnectTimeout(15000)
      // 设置读取远程返回的数据时间：60000毫秒
      connection.setReadTimeout(60000)
      connection.setRequestProperty("loginType", "local_login")
      // 发送请求
      connection.connect()
      // 通过connection连接，获取输入流
      if (connection.getResponseCode == 200) {
        is = connection.getInputStream
        // 封装输入流is，并指定字符集
        br = new BufferedReader(new InputStreamReader(is, "UTF-8"))
        // 存放数据
        var sbf = ""
        var temp: String = br.readLine()
        while ( {
          temp != null
        }) {
          sbf += temp
          sbf += ("\r\n")
          temp = br.readLine()
        }
        result = sbf
      }
    } catch {
      case e: MalformedURLException =>
        e.printStackTrace()
      case e: IOException =>
        e.printStackTrace()
    } finally {
      // 关闭资源
      if (null != br) try br.close()
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      if (null != is) try is.close()
      catch {
        case e: IOException =>
          e.printStackTrace()
      }
      connection.disconnect() // 关闭远程连接

    }
    result
  }

  /**
   * 解析httpJson
   *
   * @param event_key 事件类型
   * @return Map(属性名 -> 更新模式(替换/累计))
   */
  def getHttpJson(event_key: String): mutable.HashMap[String, String] = {

    val resultMap = mutable.HashMap[String, String]()
//    println(event_key)
    val httpJson = doGet(s"http://52.130.64.87/ndev-portraitcenter/v1/customerProperties/getCustomPropertiesByEventKey?eventKey=$event_key")

    implicit val formats: DefaultFormats.type = org.json4s.DefaultFormats
    println(httpJson)
    if (httpJson != null){
      val map = JsonMethods.parse(httpJson).extract[Map[String, Any]]
      val list = map("data").asInstanceOf[List[Map[String, Any]]]
      list.foreach(
        map => {
          val attributeKey = map("attributeKey").asInstanceOf[String]
          val updateMode = map("updateMode").asInstanceOf[String]
          resultMap.put(attributeKey, updateMode)
        }
      )
    }

    resultMap

  }

  def initializeHttpBroadcast(): mutable.HashMap[String, mutable.HashMap[String, String]] = {

    val map = mutable.HashMap[String, mutable.HashMap[String, String]]()

    //注册事件
    map.put("$signup", getHttpJson("$signup"))
    //添加宝宝
    map.put("$addbaby", getHttpJson("$addbaby"))
    //绑定事件
    map.put("$binding", getHttpJson("$binding"))
    //信息变更事件
    map.put("$update", getHttpJson("$update"))
    //等级变动事件
    map.put("$membertier", getHttpJson("$membertier"))
    //行为事件
    map.put("$behavior", getHttpJson("$behavior"))
    //交易事件
    map.put("$order", getHttpJson("$order"))
    //积分账户变动事件
    map.put("$uppointcount", getHttpJson("$uppointcount"))
    //积分记录变动事件
    map.put("$uppointrecord", getHttpJson("$uppointrecord"))
    //关注The North Face公众号事件
    map.put("$focus", getHttpJson("$focus"))
    //优惠券变动事件
    map.put("$coupon", getHttpJson("$coupon"))
    //支付事件
    map.put("$payment", getHttpJson("$payment"))
    //Tile事件
    map.put("$tile", getHttpJson("$tile"))
    //注销事件
    map.put("$signoff", getHttpJson("$signoff"))
    //首购事件
    map.put("$firstbuy", getHttpJson("$firstbuy"))
    //复购事件
    map.put("$rebuy", getHttpJson("$rebuy"))
    //首次完善资料事件
    map.put("$perfectInfo", getHttpJson("$perfectInfo"))

    map

  }


}
